﻿using System.Net.Http.Json;

namespace BlazorHelper;
/// <summary>
/// 使用工具时请先依赖注入以后使用
/// </summary>
public class HttpHelper
{
    /// <summary>
    /// 响应请求体信息委托
    /// </summary>
    /// <param name="message"></param>
    public delegate void _HeadersHandling(HttpResponseMessage message);
    /// <summary>
    /// 
    /// </summary>
    public readonly HttpClient _http;
    /// <summary>
    /// 
    /// </summary>
    /// <param name="http"></param>
    public HttpHelper(HttpClient http)
    {
        _http = http;
    }
    /// <summary>
    /// 发起Get请求（异步）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="_headers">响应请求体信息</param>
    /// <returns></returns>
    public async Task<T?> GetAsync<T>(string url, _HeadersHandling? _headers = null)
    {
        var message = await _http.GetAsync(url);
        if (_headers != null)
        {
            _headers(message);
        }
        return await message.Content.ReadFromJsonAsync<T?>();
    }
    /// <summary>
    /// 发起post请求（异步）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="data"></param>
    /// <param name="_headers">响应请求体信息</param>
    /// <returns></returns>
    public async Task<T?> PostAsync<T>(string url, object data,_HeadersHandling? _headers=null)
    {
        var message = await _http.PostAsJsonAsync(url, data);
        if (_headers != null)
        {
            _headers(message);
        }
        return await message.Content.ReadFromJsonAsync<T>();
    }
    /// <summary>
    /// 发起Delete请求（异步）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="_headers">响应请求体信息</param>
    /// <returns></returns>
    public async Task<T?> DeleteAsync<T>(string url, _HeadersHandling? _headers = null)
    {
        var message = await _http.DeleteAsync(url);
        if (_headers != null)
        {
            _headers(message);
        }
        return await message.Content.ReadFromJsonAsync<T>();
    }
    /// <summary>
    /// 发起Put请求（异步）
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="url"></param>
    /// <param name="data"></param>
    /// <param name="_headers">响应请求体信息</param>
    /// <returns></returns>
    public async Task<T?> PutAsync<T>(string url, object data, _HeadersHandling? _headers = null)
    {
        var message = await _http.PutAsJsonAsync(url, data);
        if (_headers != null)
        {
            _headers(message);
        }
        return await message.Content.ReadFromJsonAsync<T>();
    }
}